package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/xuri/excelize/v2"
)

/*
从网络上下载图片
*/
func getPicturesFromUrl(cellData string) ([]byte, error) {
	url := strings.TrimPrefix(cellData, "url:")
	response, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	bytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}

/*
从文件读取图片
*/
func getPicturesFromFile(cellData string) ([]byte, error) {
	filePath := strings.TrimPrefix(cellData, "file:")
	bytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}

/*
获取图片文件
*/
func getPictures(cellData string) ([]byte, error) {
	if strings.HasPrefix(cellData, "file:") {
		return getPicturesFromFile(cellData)
	}
	if strings.HasPrefix(cellData, "url:") {
		return getPicturesFromUrl(cellData)
	}
	return nil, nil
}

/*
*
获取图片并填充到表格单元格中
*/
func Pic(excelRequest *ExcelRequest, f *excelize.File, sheetName string, templateRow []string) error {
	if excelRequest.Pics == nil && len(excelRequest.Pics) == 0 {
		return nil
	}
	for sheetName, keys := range excelRequest.Pics {
		datas := excelRequest.Data[sheetName]
		for index, data := range datas {
			for _, key := range keys {
				if cellData, exists := data[key]; exists {
					//查找key在templateRow中的索引，定位单元格
					templateRowIndex := -1
					for i, str := range templateRow {
						if key == str {
							templateRowIndex = i
						}
					}
					if templateRowIndex == -1 {
						return fmt.Errorf("在模板第三行未找到列" + key + "的索引")
					}
					if templateRowIndex >= 0 && templateRowIndex <= 25 {
						return fmt.Errorf("只支持导出A-Z 26列")
					}
					charactor := string('A' + templateRowIndex)
					cellDataString, ok := cellData.(string)
					if ok {
						picBytes, err := getPictures(cellDataString)
						if err != nil {
							return err
						}
						g := excelize.GraphicOptions{
							AutoFit: true,
							ScaleX:  0.5,
							ScaleY:  0.5,
						}
						p := excelize.Picture{
							Extension: "",
							File:      picBytes,
							Format:    &g,
						}
						index = index + 1
						f.AddPictureFromBytes(sheetName, charactor+fmt.Sprint(index), &p)

					} else {
						return fmt.Errorf("数据转换失败!")
					}
				} else {
					return fmt.Errorf("在" + sheetName + "这个sheet页中未找到" + "pics中定义的列字段" + "key")
				}
			}
		}

	}
	return nil
}
